<?php
if (!defined('ABSPATH')) exit;
class HYWL_AI {
    private static $instance = null;
    private $option_key = 'hywl_ai_options';
    private $meta_key = '_hywl_ai_summary';
    private $api_url = 'https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie_speed';
    private $token_url = 'https://aip.baidubce.com/oauth/2.0/token';
    private $options = [];
    private $appearance_defaults = [
        'typed' => 1,
        'speed' => 50
    ];

    public static function get_instance() {
        if (!self::$instance) self::$instance = new self();
        return self::$instance;
    }
    private function __construct() {
        $this->write_debug_log('HYWL_AI __construct 被调用');
        $this->options = get_option($this->option_key, []);
        add_filter('the_content', [$this, 'inject_summary'], 5);
        add_action('admin_post_hywl_ai_refresh', [$this, 'handle_refresh']);
        add_action('admin_enqueue_scripts', [$this, 'admin_assets']);
    }
    // 前端插入AI摘要
    public function inject_summary($content) {
        $this->write_debug_log('inject_summary 强制插入摘要, post_id=' . (get_the_ID() ?: 'null'));
        global $post;
        $summary = get_post_meta($post->ID, $this->meta_key, true);
        $appearance = $this->get_appearance_options();
        if (!$summary) {
            $summary = $this->generate_summary($post->post_title, $post->post_content);
            if ($summary) update_post_meta($post->ID, $this->meta_key, $summary);
        }
        if ($summary) {
            $box = '<div class="hywl-ai-summary"><div class="hywl-ai-summary-title">AI摘要</div><div id="hywl-ai-summary-content" class="hywl-ai-summary-content" data-typed="'.$appearance['typed'].'" data-speed="'.$appearance['speed'].'">'.esc_html($summary).'</div></div>';
            // 加载打字机JS
            add_action('wp_footer', function() use ($appearance) {
                if ($appearance['typed']) {
                    echo '<script src="'.HYWL_AI_URL.'assets/typed.js?v=2"></script>';
                }
            });
            return $box . $content;
        }
        return $content;
    }
    // 生成摘要
    public function generate_summary($title, $content) {
        $api_key = $this->options['api_key'] ?? '';
        $secret_key = $this->options['secret_key'] ?? '';
        $this->write_debug_log('generate_summary called, title=' . $title);
        if (!$api_key || !$secret_key) {
            $this->write_debug_log('API Key 或 Secret Key 为空');
            return '';
        }
        $token = $this->get_access_token($api_key, $secret_key);
        $this->write_debug_log('token: ' . $token);
        if (!$token) {
            $this->write_debug_log('获取token失败');
            return '';
        }
        $prompt = '请用简洁中文总结以下文章内容，突出重点，适合展示在卡片摘要：\n标题：'.$title.'\n正文：'.wp_trim_words(strip_tags($content), 300, '...');
        $body = json_encode([
            'messages' => [
                ['role' => 'user', 'content' => $prompt]
            ]
        ]);
        $this->write_debug_log('请求body: ' . $body);
        $response = wp_remote_post($this->api_url.'?access_token='.$token, [
            'headers' => ['Content-Type' => 'application/json'],
            'body' => $body,
            'timeout' => 15
        ]);
        $resp_body = wp_remote_retrieve_body($response);
        $this->write_debug_log('接口返回: ' . $resp_body);
        if (is_wp_error($response)) {
            $this->write_debug_log('wp_remote_post 错误: ' . $response->get_error_message());
            return '';
        }
        $data = json_decode($resp_body, true);
        $result = $data['result'] ?? '';
        // 去掉"卡片摘要："等前缀
        $result = preg_replace('/^(卡片摘要|摘要|AI摘要|内容摘要)[:：\s]+/u', '', $result);
        $this->write_debug_log('最终摘要: ' . $result);
        return $result;
    }
    // 获取access_token
    private function get_access_token($api_key, $secret_key) {
        $transient_key = 'hywl_ai_baidu_token';
        $token = get_transient($transient_key);
        if ($token) return $token;
        $url = $this->token_url.'?grant_type=client_credentials&client_id='.$api_key.'&client_secret='.$secret_key;
        $response = wp_remote_get($url, ['timeout' => 10]);
        if (is_wp_error($response)) return '';
        $data = json_decode(wp_remote_retrieve_body($response), true);
        if (!empty($data['access_token'])) {
            set_transient($transient_key, $data['access_token'], $data['expires_in'] ?? 2592000);
            return $data['access_token'];
        }
        return '';
    }
    // 后台设置页
    public static function admin_page() {
        $self = self::get_instance();
        if (isset($_POST['hywl_ai_save'])) {
            check_admin_referer('hywl_ai_save');
            $opts = [
                'api_key' => sanitize_text_field($_POST['hywl_ai_api_key'] ?? ''),
                'secret_key' => sanitize_text_field($_POST['hywl_ai_secret_key'] ?? '')
            ];
            update_option($self->option_key, $opts);
        }
        if (isset($_POST['hywl_ai_appearance_save'])) {
            check_admin_referer('hywl_ai_appearance_save');
            $appearance = [
                'typed' => isset($_POST['hywl_ai_typed']) ? 1 : 0,
                'speed' => intval($_POST['hywl_ai_speed'] ?? 50)
            ];
            update_option('hywl_ai_appearance', $appearance);
            echo '<div class="updated"><p>外观设置已保存</p></div>';
        }
        $opts = get_option($self->option_key, []);
        $appearance = $self->get_appearance_options();
        echo '<div class="wrap hywl-ai-admin-wrap">';
        echo '<h1 style="margin-bottom:18px;">🤖 HYWL AI 摘要插件设置</h1>';
        // API配置卡片
        echo '<div class="card" style="max-width:600px;margin-bottom:24px;">';
        echo '<h2 style="font-size:18px;margin-bottom:12px;">API 配置</h2>';
        echo '<form method="post" style="margin-bottom:0;">';
        wp_nonce_field('hywl_ai_save');
        echo '<table class="form-table"><tr><th style="width:120px;">API Key</th><td><input type="text" name="hywl_ai_api_key" value="'.esc_attr($opts['api_key'] ?? '').'" size="40" style="width:320px;"></td></tr>';
        echo '<tr><th>Secret Key</th><td><input type="text" name="hywl_ai_secret_key" value="'.esc_attr($opts['secret_key'] ?? '').'" size="40" style="width:320px;"></td></tr></table>';
        echo '<p><button type="submit" name="hywl_ai_save" class="button button-primary">保存设置</button></p>';
        echo '</form>';
        echo '</div>';
        // 摘要刷新卡片
        echo '<div class="card" style="max-width:600px;margin-bottom:24px;">';
        echo '<h2 style="font-size:18px;margin-bottom:12px;">摘要刷新</h2>';
        echo '<form method="post" action="'.admin_url('admin-post.php').'" style="margin-bottom:0;">';
        echo '<input type="hidden" name="action" value="hywl_ai_refresh">';
        echo '<input type="number" name="post_id" placeholder="文章ID" required style="width:180px;"> ';
        echo '<button type="submit" class="button button-secondary">刷新该文章 AI 摘要</button>';
        echo '</form>';
        echo '<p style="color:#888;font-size:13px;margin-top:8px;">输入文章ID，刷新该文章的AI摘要（如内容有更新时使用）。</p>';
        echo '</div>';
        // 外观设置卡片
        echo '<div class="card" style="max-width:600px;">';
        echo '<h2 style="font-size:18px;margin-bottom:12px;">AI 摘要外观设置</h2>';
        echo '<form method="post">';
        wp_nonce_field('hywl_ai_appearance_save');
        echo '<table class="form-table">';
        echo '<tr><th style="width:120px;">打字机动画</th><td><label><input type="checkbox" name="hywl_ai_typed" value="1"'.($appearance['typed']?' checked':'').'> 启用</label></td></tr>';
        echo '<tr><th>动画速度</th><td><input type="number" name="hywl_ai_speed" value="'.esc_attr($appearance['speed']).'" min="10" max="500"> ms/字</td></tr>';
        echo '</table>';
        echo '<p><button type="submit" name="hywl_ai_appearance_save" class="button">保存外观设置</button></p>';
        echo '</form>';
        echo '</div>';
        echo '<div style="margin-top:32px;color:#aaa;font-size:13px;">HYWL AI 摘要插件 &copy; 幻影网络科技www.52hyjs.com</div>';
        echo '</div>';
    }
    // 处理摘要刷新
    public function handle_refresh() {
        if (!current_user_can('manage_options')) wp_die('权限不足');
        $post_id = intval($_POST['post_id'] ?? 0);
        if ($post_id) {
            $post = get_post($post_id);
            if ($post && $post->post_type === 'post') {
                delete_post_meta($post_id, $this->meta_key);
                $summary = $this->generate_summary($post->post_title, $post->post_content);
                if ($summary) update_post_meta($post_id, $this->meta_key, $summary);
            }
        }
        wp_redirect(admin_url('options-general.php?page=hywl-ai&refreshed=1'));
        exit;
    }
    // 后台样式
    public function admin_assets($hook) {
        if ($hook !== 'settings_page_hywl-ai') return;
        wp_enqueue_style('hywl-ai-admin', HYWL_AI_URL.'assets/ai-summary.css', [], '1.0.0');
    }
    private function get_appearance_options() {
        $opts = get_option('hywl_ai_appearance', []);
        return array_merge($this->appearance_defaults, $opts);
    }
    private function write_debug_log($msg) {
        $file = HYWL_AI_DIR . 'hywl-ai-debug.log';
        $date = date('Y-m-d H:i:s');
        file_put_contents($file, "[$date] $msg\n", FILE_APPEND);
    }
} 